package com.wjf.birdfish.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class UserLoginContext {
	private static UserLoginContext INSTANCE = null;
	private static Map<String,Long> loginUserList = null;
	
	private UserLoginContext(){}
	public static UserLoginContext getInstance() {
		
		if(loginUserList == null){
			loginUserList = new HashMap<String, Long>();
		}
		
		if(INSTANCE == null){
			INSTANCE = new UserLoginContext();
		}
		
		return INSTANCE;
	}
	
	public synchronized void  addUser(String userId){
		if(!loginUserList.containsKey(userId)){
			loginUserList.put(userId, new Date().getTime());
		}
	}
	
	public synchronized void updateUserTime(String userId,Long time){
		if(loginUserList.containsKey(userId)){
			loginUserList.remove(userId);
			loginUserList.put(userId, time);
		}
	}
	
	public synchronized void removeUser(String userId){
		if(loginUserList.containsKey(userId)){
			loginUserList.remove(userId);
		}
	}
	
	public Map<String,Long> getLoginedUserList(){
		return copyMap(loginUserList);
	}
	
	private Map<String, Long> copyMap(Map<String, Long> map) {
		Map<String, Long> newMap = new HashMap<String, Long>();
		for (Map.Entry<String, Long> entry : map.entrySet()) {
			if (entry.getValue() != null) {
				newMap.put(entry.getKey(), entry.getValue());
			}
		}

		return newMap; 

	} 


	
	public static void destory(){
		INSTANCE = null;
		loginUserList = null;
	}
}
